from bs4 import BeautifulSoup

import common.OsUtil as ost
from common.RequestUtil import RequestUtil


class AdapterBsAndRequest(object):
    def __init__(self, domain_path=None):
        self.domain = domain_path
        self.__os_util = ost.OsUtil()

    def get_request_item(self, url=None, path=None):
        """
            通过Request获取指定网址信息
            :param url: 指定的全部网址
            :param path: 指定Uri,用于和domain拼结
            :return:
        """
        url_path = url
        if self.domain is not None and url is None:
            url_path = "{0}/{1}".format(self.domain, path)
        return RequestUtil.get(url_path)

    def res_soup_from_request(self, url=None, path=None):
        '''
        用于Http形式获取bs4结构
        :param url: 完整的Url
        :param path: Uri
        :return:
        '''
        req_body = self.get_request_item(url, path)
        return self.res_soup_from_context(req_body)

    def res_soup_from_context(self, text=None):
        '''
        用于基础于内容转换为bs4结构对象
        :param text:
        :return:
        '''
        rt_value = None
        if text:
            rt_value = BeautifulSoup(text, 'html5lib')
        return rt_value

    def file_open_obj(self, file_os_path):
        result = self.__os_util.exists_file(file_os_path)
        if result <= 0:
            return None

        r_obj = open(file_os_path, "r")
        rs_obj = str(r_obj.readlines())
        r_obj.close()
        return rs_obj

    def res_save_object(self, folder=None, file_name=None, res_data=None):
        raise None
